package co.wizardattack.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.detector.ClickDetector;
import org.andengine.input.touch.detector.ClickDetector.IClickDetectorListener;
import org.andengine.input.touch.detector.ScrollDetector;
import org.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.andengine.input.touch.detector.SurfaceScrollDetector;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;

import communication.MessageDistpacher;

import protocol.ConnectionDiscover;
import protocol.GameToConnect;
import protocol.OnConnectionUpdatesListener;
import protocol.User;
import co.wizardattack.constants.ResourcesNames;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.Toast;

/**
 * 
 * @author Knoll Florian
 * @email myfknoll@gmail.com
 *
 */
public class MenuScrollerActivity extends SimpleBaseGameActivity implements IScrollDetectorListener, IOnSceneTouchListener, IClickDetectorListener, OnConnectionUpdatesListener {

	/**
	 * Constantes
	 */
	protected static int CAMERA_WIDTH = 1080;
	protected static int CAMERA_HEIGHT = 720;
	protected static int FONT_SIZE = 10;	
	protected static int PADDING = CAMERA_WIDTH/6;
	protected static int MENUITEMS = 3;
	/**
	 * Atributos
	 */
	private Scene sceneMenu;
	private Camera cameraMenu;
	private Font fontMenu; 
	private BitmapTextureAtlas atlasFont; 
	private BitmapTextureAtlas atlasMenu; 	
	private TextureRegion textureL;
	private TextureRegion textureR;
	private Sprite spriteL;
	private Sprite spriteR;
	//fondo
	private BitmapTextureAtlas atlasBackground;
	private TextureRegion textureBackground;
	private Sprite spriteBackground;
	// Scrolling
	private SurfaceScrollDetector scrollDetectorMenu;
	private ClickDetector clickDetectorMenu;
	private float mMinX = 0;
	private float mMaxX = 0;
	private float mCurrentX = 0;
	private int iItemClicked = -1;
	private Rectangle rectangleScrollBar;        
	private List<TextureRegion> columns = new ArrayList<TextureRegion>();
	
	/**
	 * Connection
	 */
	private ConnectionDiscover discover;
	
	/**
	 * Metodos
	 */
	
	@Override
	protected void onCreate(Bundle pSavedInstanceState) {
		discover = new ConnectionDiscover("wifichatroom", util.NetworkUtility.getIpAddr((WifiManager) getSystemService(WIFI_SERVICE)), this, MessageDistpacher.INSTANCE);
		super.onCreate(pSavedInstanceState);
	}

	@Override
	public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
		this.clickDetectorMenu.onTouchEvent(pSceneTouchEvent);
		this.scrollDetectorMenu.onTouchEvent(pSceneTouchEvent);
		return true;
	}

	private void CreateMenuBoxes() {
		this.spriteBackground = new Sprite(1080 / 2, 720 / 2 , textureBackground,  this.getVertexBufferObjectManager());
		this.sceneMenu.attachChild(spriteBackground);

		int posX = CAMERA_WIDTH/2;
		int posY = CAMERA_HEIGHT/4;
		//current item counter
		int iItem = 1;
		for (int x = 0; x < columns.size(); x++) {
			//On Touch, save the clicked item in case it's a click and not a scroll.
			final int itemToLoad = iItem;
			Sprite sprite = new Sprite(posX,posY,columns.get(x), getVertexBufferObjectManager()){
				public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					iItemClicked = itemToLoad;
					return false;
				}        			 
			};
			iItem++;
			this.sceneMenu.attachChild(sprite);
			this.sceneMenu.registerTouchArea(sprite);
			posX += 20 + PADDING+sprite.getWidth();
		}
		mMaxX = posX - CAMERA_WIDTH;		

		//set the size of the scrollbar
		//float scrollbarsize = CAMERA_WIDTH/((mMaxX+CAMERA_WIDTH)/CAMERA_WIDTH);
		//scrollBar = new Rectangle(0,CAMERA_HEIGHT-20,scrollbarsize, 20, getVertexBufferObjectManager());

		//todo en cero para que no aparezca la barra	
		rectangleScrollBar = new Rectangle(0, 0, 0, 0, getVertexBufferObjectManager());		
		rectangleScrollBar.setColor(1,0,0);		
		this.sceneMenu.attachChild(rectangleScrollBar);		
		spriteL = new Sprite(0,CAMERA_HEIGHT/4,textureL, getVertexBufferObjectManager());

		//se le toma el ancho de spriteL para poder posicionar al spriteR. son del mismo ancho.
		spriteR = new Sprite(cameraMenu.getCenterX()+CAMERA_WIDTH/2-spriteL.getWidth(),CAMERA_HEIGHT/4,textureR, getVertexBufferObjectManager());
		//fondo

		this.sceneMenu.attachChild(spriteR);
		spriteL.setVisible(false);
		this.sceneMenu.attachChild(spriteL);
	}


	//Here is where you call the item load.
	private void loadLevel(final int iLevel) {
		if (iLevel != -1) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(MenuScrollerActivity.this, "Load Item" + String.valueOf(iLevel), Toast.LENGTH_SHORT).show();
					iItemClicked = -1;
				}
			});
		}
	}

	@Override
	public EngineOptions onCreateEngineOptions() {
		this.cameraMenu = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), cameraMenu);
		engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
		return engineOptions;
	}

	@Override
	public void onClick(ClickDetector pClickDetector, int pPointerID, float pSceneX, float pSceneY) {
		loadLevel(iItemClicked);		
	}

	@Override
	public void onScrollStarted(ScrollDetector pScollDetector, int pPointerID, float pDistanceX, float pDistanceY) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onScroll(ScrollDetector pScollDetector, int pPointerID, float pDistanceX, float pDistanceY) {
		//Disable the menu arrows left and right (15px padding)
		if(cameraMenu.getXMin()<=15)
			spriteL.setVisible(false);
		else
			spriteL.setVisible(true);

		if(cameraMenu.getXMin()>mMaxX-15)
			spriteR.setVisible(false);
		else
			spriteR.setVisible(true);

		//Return if ends are reached
		if ( ((mCurrentX - pDistanceX) < mMinX)  ){                	
			return;
		}else if((mCurrentX - pDistanceX) > mMaxX){
			return;
		}
		//Center camera to the current point
		this.cameraMenu.offsetCenter(-pDistanceX,0 );
		mCurrentX -= pDistanceX;

		//Set the scrollbar with the camera
		float tempX =cameraMenu.getCenterX()-CAMERA_WIDTH/2;

		// add the % part to the position
		tempX+= (tempX/(mMaxX+CAMERA_WIDTH))*CAMERA_WIDTH;

		//set the position
		rectangleScrollBar.setPosition(tempX, rectangleScrollBar.getY());

		//set the arrows for left and right
		spriteR.setPosition(cameraMenu.getCenterX()+CAMERA_WIDTH/2-spriteR.getWidth(),spriteR.getY());
		spriteL.setPosition(cameraMenu.getCenterX()-CAMERA_WIDTH/2+spriteL.getWidth(),spriteL.getY());
		spriteBackground.setPosition(cameraMenu.getCenterX(),cameraMenu.getCenterY());

		//Because Camera can have negativ X values, so set to 0
		if(this.cameraMenu.getXMin()<0){
			this.cameraMenu.offsetCenter(0,0 );
			mCurrentX=0;
		}
	}

	@Override
	public void onScrollFinished(ScrollDetector pScollDetector,
			int pPointerID, float pDistanceX, float pDistanceY) {
		// TODO Auto-generated method stub
	}

	@Override
	protected void onCreateResources() throws IOException {
		// Paths
		FontFactory.setAssetBasePath("fonts/");
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("images/");

		//fondo
		this.atlasBackground = new BitmapTextureAtlas(getTextureManager(), 1080, 720, TextureOptions.DEFAULT);
		this.textureBackground = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasBackground, this, "farm_background.jpg", 0, 0);
		atlasBackground.load();

		// Font
		this.atlasFont = new BitmapTextureAtlas(getTextureManager(), 256, 256);
		this.fontMenu = FontFactory.createFromAsset(getFontManager(), atlasFont, getAssets(), ResourcesNames.FUENTE_NOMBRE, 100, true, Color.WHITE);
		this.mEngine.getTextureManager().loadTexture(this.atlasFont);
		this.mEngine.getFontManager().loadFonts(this.fontMenu);

		//Images for the menu
		for (int i = 0; i < MENUITEMS; i++) {			
			//BitmapTextureAtlas mMenuBitmapTextureAtlas = new BitmapTextureAtlas(getTextureManager(), 1080,256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
			//TextureRegion mMenuTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuBitmapTextureAtlas, this, "menu"+i+".png", 0, 0);
			//TextureRegion mMenuTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuBitmapTextureAtlas, this, "accpluma.png", 0, 0);
			BitmapTextureAtlas mMenuBitmapTextureAtlas = new BitmapTextureAtlas(getTextureManager(), 1080, 720, TextureOptions.DEFAULT);
			TextureRegion mMenuTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mMenuBitmapTextureAtlas, this, "pollo_esperando.png", 0, 0);
			this.mEngine.getTextureManager().loadTexture(mMenuBitmapTextureAtlas);
			columns.add(mMenuTextureRegion);
		}
		//Textures for menu arrows
		this.atlasMenu = new BitmapTextureAtlas(getTextureManager(), 1080, 720, TextureOptions.DEFAULT);
		this.textureL = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasMenu, this, "fl.png", 0, 0);
		this.textureR = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasMenu, this, "fr.png",65, 0);
		this.mEngine.getTextureManager().loadTexture(atlasMenu);		
	}

	@Override
	protected Scene onCreateScene() {

		//
		this.mEngine.registerUpdateHandler(new FPSLogger());
		this.sceneMenu = new Scene();

		//this.mScene.setBackground(new ColorBackground(0, 0, 0));
		this.scrollDetectorMenu = new SurfaceScrollDetector(this);
		this.clickDetectorMenu = new ClickDetector(this);
		this.sceneMenu.setOnSceneTouchListener(this);
		//this.mScene.setTouchAreaBindingEnabled(true);
		//this.mScene.setOnSceneTouchListenerBindingEnabled(true);
		this.sceneMenu.setTouchAreaBindingOnActionDownEnabled(true);
		this.sceneMenu.setOnSceneTouchListenerBindingOnActionDownEnabled(true);
		CreateMenuBoxes();		
		return sceneMenu;
	}

	@Override
	public void onGamesListUpdated(Collection<GameToConnect> users) {
		Toast.makeText(this, "onGamesListUpdated", 0).show();
	}

	@Override
	public void onGameStart(long timeDifference, int countDown) {
		Toast.makeText(this, "onGameStart", 0).show();
	}

	@Override
	public void onUsersListUpdated(Collection<User> users) {
		Toast.makeText(this, "onUsersListUpdated", 0).show();
	}

	@Override
	public void onConnectionConfirmed(boolean confirmed) {
		Toast.makeText(this, "onConnectionConfirmed", 0).show();
	}
}
